using StackExchange.Redis;

namespace SN.WebApi.Commons;

public class SimpleRedis
{
    private readonly string _name;
    private readonly IDatabase _db;
    private const string KEY_PREFIX = "lock:user";
    private static string ID_PREFIX = Guid.NewGuid().ToString().Replace("-","");

    public SimpleRedis(string name, IDatabase db)
    {
        _name = name;
        _db = db;
    }

    public bool Lock(string name)
    {
        string lockKey = KEY_PREFIX + name;
        var lockValue = ID_PREFIX + "-"+Thread.CurrentThread.ManagedThreadId;
        try{
        bool acquired = _db.LockTake(lockKey, lockValue, TimeSpan.FromSeconds(10));
        return acquired;

        }catch{
            return false;
        }
    }

    public void UnLock(string name)
    {
        string lockKey = KEY_PREFIX + name;
        var lockValue = ID_PREFIX + "-"+Thread.CurrentThread.ManagedThreadId;
        _db.LockRelease(lockKey, lockValue);
    }
   
}
